﻿using Newtonsoft.Json;
using Wips.Infrastructure.Helpers;
using Wips.Infrastructure.Model;
using Wips.Infrastructure.Options;

namespace Wips.Infrastructure.Middlewares
{
    /// <summary>
    /// 请求加密 双向校验
    /// </summary>
    public class Rsa2Middleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<Rsa2Middleware> _logger;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        /// <param name="loggerFactory"></param>
        /// <param name="sqlSugarClient"></param>
        public Rsa2Middleware(RequestDelegate next, ILoggerFactory loggerFactory, IConfiguration configuration)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<Rsa2Middleware>();
            _configuration = configuration;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public async Task Invoke(HttpContext context)
        {
            if (!context.Request.Path.HasValue || !context.Request.Path.Value.StartsWith("/api/"))
            {
                await _next(context);
                return;
            }
            // 上传暂时不校验
            if (context.Request.Path.Value == "/api/agent/upload")
            {
                await _next(context);
                return;
            }
            // 获取请求头上的加密信息
            var sign = context.Request.Headers["sign"].ToString();
            if (string.IsNullOrEmpty(sign))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("error");
                return;
            }

            var authConfig = _configuration.GetSection("AuthConfig").Get<AuthConfig>();
            if (authConfig == null)
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("not config");
                return;
            }
            var allParams = "";
            if (context.Request.Path == Consts.MapSaveFileText)
            {
                var request =JsonConvert.DeserializeObject<SaveFileTextRequest>( Extensions.GetRequestBodyString(context));
                
            
                allParams = context.Request.Path.ToString().ToLower() + request!.RollString;
            }
            else
            {
                // 获取所有参数，用来做校验的字符串
                allParams = context.Request.Path.ToString().ToLower()
                   + Extensions.GetRequestQueryString(context)
                   + Extensions.GetRequestBodyString(context);
            }

            try
            {
                allParams = System.Text.RegularExpressions.Regex.Unescape(@allParams);
            }
            catch (Exception)
            {

            }

            // 如果公钥不为空，则根据公钥解密校验
            if (!string.IsNullOrEmpty(authConfig.PublicKey))
            {
                var vaild = Rsa2Helper.VerifyDataWithPublicKey(allParams, sign, authConfig.PublicKey);
                if (!vaild)
                {
                    context.Response.StatusCode = 401;
                    await context.Response.WriteAsync("Invalid sign");
                    return;
                }
            }
            else
            {
                string decryptedData = Rsa2Helper.DecryptWithPrivateKey(sign, authConfig.PrivateKey);
                try
                {
                    decryptedData = System.Text.RegularExpressions.Regex.Unescape(@decryptedData);
                }
                catch (Exception)
                {

                }

                if (allParams != decryptedData)
                {
                    context.Response.StatusCode = 401;
                    await context.Response.WriteAsync("Invalid sign");
                    return;
                }
            }
            await _next(context);
            return;

        }





    }
}
